package com.edu.controller;

import com.edu.bean.Book;
import com.edu.bean.User;
import com.edu.service.BookService;
import com.edu.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private BookService bookService;

    @GetMapping("/login")
    public ModelAndView login(String userName, String password, HttpSession session) {
        ModelAndView mav = new ModelAndView();
        Map<String, Object> login = userService.login(userName, password);
        Object loginUser = login.get("loginUser");
        Page<Book> allBook = bookService.getAllBook(1,5);
        PageInfo<Book> bookPageInfo = allBook.toPageInfo();
        if (loginUser != null) {
            session.setAttribute("loginUser",loginUser);
            mav.addObject("loginUser", loginUser);
            mav.addObject("bookPageInfo",bookPageInfo);
            mav.addObject("allBook", allBook);
            mav.setViewName("/book.jsp");
        } else {
            Object msg = login.get("msg");
            mav.addObject("msg", msg);
            mav.setViewName("/login.jsp");
        }
        return mav;
    }

    @PostMapping("/register")
    public ModelAndView register(String userName, String password) {
        ModelAndView mav = new ModelAndView();
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        int i = userService.addUser(user);
        if (i == 1) {
            mav.setViewName("/index.jsp");
        }
        return mav;
    }
}
